/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.quanshu.exchange.ui.gui.message.chat.row;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.NinePatch;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.widget.ImageView;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMImageMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.util.ImageUtils;
import com.hyphenate.util.PathUtil;
import com.quanshu.exchange.support.chat.ChatCommonUtils;
import com.quanshu.exchange.ui.base.MyApplication;

import java.io.File;

public class ChatImageUtil extends com.hyphenate.util.ImageUtils {

    public static String getImagePath(String remoteUrl) {
        String imageName = remoteUrl.substring(remoteUrl.lastIndexOf("/") + 1, remoteUrl.length());
        String path = PathUtil.getInstance().getImagePath() + "/" + imageName;
        return path;

    }

    public static String getThumbnailImagePath(String thumbRemoteUrl) {
        String thumbImageName = thumbRemoteUrl.substring(thumbRemoteUrl.lastIndexOf("/") + 1, thumbRemoteUrl.length());
        String path = PathUtil.getInstance().getImagePath() + "/" + "th" + thumbImageName;
        return path;
    }

//    /**
//     * 传入方向和要加载的Bitmap显示最终的聊天图片气泡样式
//     *
//     * @param context
//     * @param direct
//     * @param bitmap_in
//     * @return
//     */
//    public static Bitmap showFromChatImage(final Context context, final EMMessage.Direct direct, final Bitmap bitmap_in) {
//        int bgResourceId = R.drawable.chatfrom_bg;
//        Bitmap bitmap_bg = BitmapFactory.decodeResource(context.getResources(), bgResourceId);
//        Bitmap bp = getRoundCornerImage(bitmap_bg, bitmap_in);
//        Bitmap shardImage = getShardImage(bitmap_bg, bp, direct);
//        bitmap_bg = null;
//        bp = null;
//        return shardImage;
//    }
//
//    public static Bitmap showToAllChatImage(final Context context, final EMMessage.Direct direct, final Bitmap bitmap_in) {
//        int bgResourceId = R.drawable.chatto_bg_all;
//        Bitmap bitmap_bg = BitmapFactory.decodeResource(context.getResources(), bgResourceId);
//        Bitmap bp = getRoundCornerImage(bitmap_bg, bitmap_in);
//        Bitmap shardImage = getShardImage(bitmap_bg, bp, direct);
//        bitmap_bg = null;
//        bp = null;
//        return shardImage;
//    }

//    public static Bitmap showToDownChatImage(final Context context, final EMMessage.Direct direct, final Bitmap bitmap_in) {
//        int bgResourceId = R.drawable.chatto_bg_down;
//        Bitmap bitmap_bg = BitmapFactory.decodeResource(context.getResources(), bgResourceId);
//        Bitmap bp = getRoundCornerImage(bitmap_bg, bitmap_in);
//        Bitmap shardImage = getShardImage(bitmap_bg, bp, direct);
//        bitmap_bg = null;
//        bp = null;
//        return shardImage;
//    }

    private static Bitmap getRoundCornerImage(Bitmap bitmap_bg, Bitmap bitmap_in) {
        Bitmap roundConcerImage = Bitmap.createBitmap(350, 540, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(roundConcerImage);
        Paint paint = new Paint();
        Rect rect = new Rect(0, 0, 350, 540);
        Rect rectF = new Rect(0, 0, bitmap_in.getWidth(), bitmap_in.getHeight());
        paint.setAntiAlias(true);
        NinePatch patch = new NinePatch(bitmap_bg, bitmap_bg.getNinePatchChunk(), null);
        patch.draw(canvas, rect);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap_in, rectF, rect, paint);
        canvas = null;
        paint = null;
        return roundConcerImage;
    }

    private static Bitmap getShardImage(Bitmap bitmap_bg, Bitmap bitmap_in, EMMessage.Direct direct) {
        Bitmap roundConcerImage = Bitmap.createBitmap(280, 432, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(roundConcerImage);
        Paint paint = new Paint();
        Rect rect = new Rect(0, 0, 280, 432);
        paint.setAntiAlias(true);
        NinePatch patch = new NinePatch(bitmap_bg, bitmap_bg.getNinePatchChunk(), null);
        patch.draw(canvas, rect);
        Rect rect2 = EMMessage.Direct.RECEIVE.equals(direct) ? new Rect(1, 1, 279, 431) : new Rect(1, 1, 279, 431);
        canvas.drawBitmap(bitmap_in, rect, rect2, paint);
        canvas = null;
        paint = null;
        return roundConcerImage;
    }


    /**
     * load image into image view
     *
     * @param thumbernailPath
     * @param iv
     * @return the image exists or not
     */
    public static boolean showFromImageView(EMImageMessageBody imgBody, final String thumbernailPath, final ImageView iv, final String localFullSizePath, final EMMessage message, Context context) {
        // first check if the thumbnail image already loaded into cache
        Bitmap bitmap = ChatImageCache.getInstance().get(thumbernailPath);
        final EMMessage.Direct direct = message.direct();
        iv.setImageDrawable(null);
        if (bitmap != null) {
            iv.setImageBitmap(bitmap);
//            iv.setImageBitmap(ChatImageUtil.showFromChatImage(context, direct, bitmap));
            return true;
        } else {
            new AsyncTask<Object, Void, Bitmap>() {
                @Override
                protected Bitmap doInBackground(Object... args) {
                    File file = new File(thumbernailPath);
                    if (file.exists()) {
                        return ChatImageUtil.decodeScaleImage(thumbernailPath, 480, 480);
                    } else if (new File(imgBody.thumbnailLocalPath()).exists()) {
                        return ChatImageUtil.decodeScaleImage(imgBody.thumbnailLocalPath(), 480, 480);
                    } else {
                        if (message.direct() == EMMessage.Direct.SEND) {
                            if (localFullSizePath != null && new File(localFullSizePath).exists()) {
                                return ChatImageUtil.decodeScaleImage(localFullSizePath, 480, 480);
                            } else {
                                return null;
                            }
                        } else {
                            return null;
                        }
                    }
                }

                protected void onPostExecute(Bitmap image) {
                    if (image != null) {
                        iv.setImageBitmap(image);
//                        iv.setImageBitmap(ChatImageUtil.showFromChatImage(context, direct, image));
                        ChatImageCache.getInstance().put(thumbernailPath, image);
                    } else {
                        if (message.status() == EMMessage.Status.FAIL) {
                            new Thread(() -> EMClient.getInstance().chatManager().downloadThumbnail(message)).start();
                        }

                    }
                }
            }.execute();

            return true;
        }
    }

    /**
     * load image into image view
     *
     * @param thumbernailPath
     * @param iv
     * @return the image exists or not
     */
    public static boolean showToAllImageView(EMImageMessageBody imgBody, final String thumbernailPath, final ImageView iv, final String localFullSizePath, final EMMessage message, Context context) {
        // first check if the thumbnail image already loaded into cache
        Bitmap bitmap = ChatImageCache.getInstance().get(thumbernailPath);
        final EMMessage.Direct direct = message.direct();
        iv.setImageDrawable(null);
        if (bitmap != null) {
            // thumbnail image is already loaded, reuse the drawable
            iv.setImageBitmap(bitmap);
//            iv.setImageBitmap(ChatImageUtil.showToAllChatImage(context, direct, bitmap));
            return true;
        } else {
            new AsyncTask<Object, Void, Bitmap>() {

                @Override
                protected Bitmap doInBackground(Object... args) {
                    File file = new File(thumbernailPath);
                    if (file.exists()) {
                        return ChatImageUtil.decodeScaleImage(thumbernailPath, 480, 480);
                    } else if (new File(imgBody.thumbnailLocalPath()).exists()) {
                        return ChatImageUtil.decodeScaleImage(imgBody.thumbnailLocalPath(), 480, 480);
                    } else {
                        if (message.direct() == EMMessage.Direct.SEND) {
                            if (localFullSizePath != null && new File(localFullSizePath).exists()) {
                                return ChatImageUtil.decodeScaleImage(localFullSizePath, 480, 480);
                            } else {
                                return null;
                            }
                        } else {
                            return null;
                        }
                    }
                }

                protected void onPostExecute(Bitmap image) {
                    if (image != null) {
                        iv.setImageBitmap(image);
//                        iv.setImageBitmap(ChatImageUtil.showToAllChatImage(context, direct, image));
                        ChatImageCache.getInstance().put(thumbernailPath, image);
                    } else {
                        if (message.status() == EMMessage.Status.FAIL) {
                            new Thread(() -> EMClient.getInstance().chatManager().downloadThumbnail(message)).start();
                        }

                    }
                }
            }.execute();

            return true;
        }
    }

    /**
     * @return the image exists or not
     */
    public static boolean showToAllVideoView(final String localThumb, final ImageView iv, final EMMessage message, Context context) {
        Bitmap bitmap = ChatImageCache.getInstance().get(localThumb);
        final EMMessage.Direct direct = message.direct();
        iv.setImageDrawable(null);
        if (bitmap != null) {
            iv.setImageBitmap(bitmap);
//            iv.setImageBitmap(ChatImageUtil.showToAllChatImage(context, direct, bitmap));
            return true;
        } else {
            new AsyncTask<Object, Void, Bitmap>() {

                @Override
                protected Bitmap doInBackground(Object... args) {
                    if (new File(localThumb).exists()) {
                        return ImageUtils.decodeScaleImage(localThumb, 480, 480);
                    } else {
                        return null;
                    }
                }

                protected void onPostExecute(Bitmap result) {
                    if (result != null) {
                        iv.setImageBitmap(result);
//                        iv.setImageBitmap(ChatImageUtil.showToAllChatImage(context, direct, result));
                        ChatImageCache.getInstance().put(localThumb, result);

                    } else {
                        if (message.status() == EMMessage.Status.FAIL) {
                            if (ChatCommonUtils.isNetWorkConnected(MyApplication.getInstance())) {
                                EMClient.getInstance().chatManager().downloadThumbnail(message);
                            }
                        }

                    }
                }
            }.execute();
            return true;
        }
    }

    /**
     * @return the image exists or not
     */
    public static boolean showFromVideoView(final String localThumb, final ImageView iv, final EMMessage message, Context context) {
        Bitmap bitmap = ChatImageCache.getInstance().get(localThumb);
        final EMMessage.Direct direct = message.direct();
        iv.setImageDrawable(null);
        if (bitmap != null) {
            iv.setImageBitmap(bitmap);
//            iv.setImageBitmap(ChatImageUtil.showFromChatImage(context, direct, bitmap));
            return true;
        } else {
            new AsyncTask<Object, Void, Bitmap>() {

                @Override
                protected Bitmap doInBackground(Object... args) {
                    if (new File(localThumb).exists()) {
                        return ImageUtils.decodeScaleImage(localThumb, 480, 480);
                    } else {
                        return null;
                    }
                }

                protected void onPostExecute(Bitmap result) {
                    if (result != null) {
                        iv.setImageBitmap(result);
//                        iv.setImageBitmap(ChatImageUtil.showFromChatImage(context, direct, result));
                        ChatImageCache.getInstance().put(localThumb, result);

                    } else {
                        if (message.status() == EMMessage.Status.FAIL) {
                            if (ChatCommonUtils.isNetWorkConnected(MyApplication.getInstance())) {
                                EMClient.getInstance().chatManager().downloadThumbnail(message);
                            }
                        }

                    }
                }
            }.execute();
            return true;
        }
    }
}
